package com.aoxin.service.impl.pay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.aoxin.mapper.SlfRechargeMapper;
import com.aoxin.mapper.opm.SlfUserMapper;
import com.aoxin.model.SlfRecharge;
import com.aoxin.model.activity.SlfRecommendMoney;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.activity.RecommendMoneyService;
import com.aoxin.service.inter.pay.PaymentService;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.ThreadLocalUtil;

/**
 * @Author: 李贵
 * @Date: Created in 16:49 2018/4/29
 * @Content:
 */
@Service
public class PaymentServiceImpl implements PaymentService{

    @Autowired
    private SlfUserMapper slfUserMapper;

    @Autowired
    private SlfRechargeMapper slfRechargeMapper;

    @Autowired
    private RecommendMoneyService recommendMoneyService;

    private static String FIRST_Charge_KEY="first_charge_threshold_value";
    
    private static String FIRST_Charge_VALUE="first_charge_threshold_proportion_value";
    
    private static String ACCUMULATIVE_RECHARGE_MONEY_KEY="accumulative_recharge_money_threshold_value";
    
    private static String ACCUMULATIVE_RECHARGE_MONEY_VALUE="accumulative_recharge_money_proportion_value";
    
    
    
    
    @Override
    @Transactional
    public void updateSynthesizeData(SlfRecharge slfRecharge,Integer userId,Integer thresholdId) {
    	/**
    	 * money  充值的钱
    	 * 
    	 * 
    	 * recharge 累计充值的钱
    	 */

		BigDecimal money = slfRecharge.getMoney();
		//测试数据
		//BigDecimal money = new BigDecimal(100);
        Assert.notNull(money, String.format(ErrorUtil.PARAMETER_NULL,"money"));
        SlfUser user = this.slfUserMapper.selectByPrimaryKey(userId);
        List<SlfRecharge> slfRechargeList = this.slfRechargeMapper.getSlfPayRecharge(userId);
        Double recharge=0.0;

        //计算累计充值金额
        for(SlfRecharge slfRecharge1 : slfRechargeList){
            recharge += slfRecharge1.getMoney().doubleValue();
        }
        //TODO 需要传递一个档位ID  暂时定义一个档位
        Integer firstChargeThresholdId=thresholdId;
        
        
        //已经获得过返利的情况
        if(recharge>=200){
              Double lfb=money.doubleValue();
              lfb=activityGiveLfb( userId, firstChargeThresholdId, lfb, money, recharge);
        	
            this.slfUserMapper.rechargeLfb(lfb,user.getUserId());
            this.slfRechargeMapper.updateSlfRecharge(slfRecharge);
        }else {
            //累计充值加上本次充值
            double result = recharge+money.doubleValue();
            //充值大于200并且小于10000的返利情况
            if(200<=result&&result<10000){
                SlfRecommendMoney slfRecommendMoney = new SlfRecommendMoney();
                slfRecommendMoney.setReferralsId(userId);
                SlfRecommendMoney slfRecommendMoney1 = this.recommendMoneyService.updateRecommendMoney(slfRecommendMoney,1);
                if(slfRecommendMoney1.getRecommendMoney()!=null && slfRecommendMoney1.getRefereeId() != null){
                    SlfUser slfUser = new SlfUser();
                    slfUser.setUserId(user.getUserId());
                    slfUser.setRmb(slfRecommendMoney1.getRecommendMoney().doubleValue());
                    slfUser.setIsWinners(1);
                    this.slfUserMapper.updateByPrimaryKeySelective(slfUser);
                }
            //累计充值大于等于10000的返利情况
            }else if(result>=10000){
                SlfRecommendMoney slfRecommendMoney = new SlfRecommendMoney();
                slfRecommendMoney.setReferralsId(userId);
                SlfRecommendMoney slfRecommendMoney1 = this.recommendMoneyService.updateRecommendMoney(slfRecommendMoney,2);
                if(slfRecommendMoney1.getRecommendMoney()!=null && slfRecommendMoney1.getRefereeId() != null){
                    SlfUser slfUser = new SlfUser();
                    slfUser.setUserId(user.getUserId());
                    slfUser.setRmb(slfRecommendMoney1.getRecommendMoney().doubleValue());
                    slfUser.setIsWinners(1);
                    this.slfUserMapper.updateByPrimaryKeySelective(slfUser);
                }
            }
            Double lfb=money.doubleValue();
            lfb=activityGiveLfb( userId, firstChargeThresholdId, lfb, money, recharge);
            //充值立方币
            this.slfUserMapper.rechargeLfb(lfb,userId);
            //修改充值记录
            this.slfRechargeMapper.updateSlfRecharge(slfRecharge);
        }
    }
    
    
    
    
    
    
    
    
    /**
     *  返回首充比例
     * @param money
     * @return
     */
    private Double calculationFirstChargeProportionValue(BigDecimal money){
    	  List<Map<String,Object>> firstChargeProportionValueList= this.slfRechargeMapper.queryFirstChargeThreshold(null);
    	  Double proportionValue=0.0;
    	  for (int i = 0,b=firstChargeProportionValueList.size(); i <b; i++) {
    		 int number= Integer.parseInt(firstChargeProportionValueList.get(i).get(FIRST_Charge_KEY).toString());
    		 int chargeMoney= money.intValue();
    		 if(chargeMoney<number){
    			 if(i==0){
    				 break;
    			 }else{
    				 proportionValue=Double.parseDouble(firstChargeProportionValueList.get(i-1).get(FIRST_Charge_VALUE).toString());
    				 break;
    			 }
    		 }else if(i==(b-1)&&chargeMoney>number){
    			 proportionValue=Double.parseDouble(firstChargeProportionValueList.get(i).get(FIRST_Charge_VALUE).toString());
    			 break;
    		 }else if(chargeMoney==number){
    			 proportionValue=Double.parseDouble(firstChargeProportionValueList.get(i).get(FIRST_Charge_VALUE).toString());
    			 break; 
    		 }
    		  
		}
    	  return proportionValue;
    	
    }
    
    /**
     * 返回累计充值比例
     * @param money
     * @return
     */
    private Integer calculationAccumulativeRechargeMoneyProportion(BigDecimal money){
    	  List<Map<String,Object>> firstChargeProportionValueList= this.slfRechargeMapper.queryAccumulativeRechargeMoneThreshold();
    	  int moneyValue=money.intValue();
    	  Integer numberKey=null;
    	  for (int i = 0,a=firstChargeProportionValueList.size(); i < a; i++) {
			int number=Integer.parseInt(firstChargeProportionValueList.get(i).get(ACCUMULATIVE_RECHARGE_MONEY_KEY).toString()); 
			if(moneyValue<number){
					if(i==0){
						break;
					}else{
						numberKey=i-1;
						break;
					}
			}else if(moneyValue>number && i==a-1){
				numberKey= i;
				break;
			}else if(moneyValue==number){
				numberKey= i;
				break;
			}
    	  }
    	  return numberKey;
    }
    
    @Override
    public boolean isFirstCharge(Integer firstChargeThresholdId){
    	   Integer userId =ThreadLocalUtil.getUser().getUserId();
    	  List<SlfRecharge> slfRechargeList = this.slfRechargeMapper.getSlfPayRecharge(userId);
    	  Integer countNumber= this.slfRechargeMapper.queryFirstChargeHistory(userId,firstChargeThresholdId);
    	  if(countNumber==0 &&slfRechargeList.size()==0 ){
    		  //首充
    		  return true;
    	  }else{
    		  //不是首充
    		  return false;
    	  }
    	  
    }








	@Override
	public List<Map<String, Object>> queryFirstChargeThreshold() {
		return slfRechargeMapper.queryFirstChargeThreshold(null);
	}
    
    
    
    
	private Double activityGiveLfb(Integer userId,Integer firstChargeThresholdId,Double lfb,BigDecimal money,Double recharge){
		Integer countNumber= this.slfRechargeMapper.queryFirstChargeHistory(userId,firstChargeThresholdId);
    	/**
      	 * 活动首充
      	 */
      //第一次充值 且充值记录为空
      if(countNumber==0){
      	//首次充值
      	   /**
           * 获取首充比例
           */
         /* Double proportionValue=calculationFirstChargeProportionValue(money);
          if(proportionValue>0){
          	   BigDecimal rechargeMoney= money;
                 //获取返现后金额 floor
                 BigDecimal proportionaMoney =new BigDecimal( rechargeMoney.multiply(new BigDecimal(proportionValue.toString())).intValue());
                 //实际得到金额
                lfb= rechargeMoney.add(proportionaMoney).doubleValue();
                // 添加首充历史记录
                this.slfRechargeMapper.insertFirstChargeHistory(userId,rechargeMoney,new BigDecimal(proportionValue.toString()),new BigDecimal(lfb));
          }*/
    	  List<Map<String,Object>>  firstChargeThreshold=this.slfRechargeMapper.queryFirstChargeThreshold(firstChargeThresholdId);
          if(firstChargeThreshold.size()>0){
          	   BigDecimal rechargeMoney= money;
          	   BigDecimal  proportionValue=new BigDecimal(firstChargeThreshold.get(0).get(FIRST_Charge_VALUE).toString());
                 //获取返现后金额 floor
                 BigDecimal proportionaMoney =new BigDecimal(rechargeMoney.multiply(proportionValue).intValue()).setScale(0,BigDecimal.ROUND_DOWN);
                 //实际得到金额
                lfb= rechargeMoney.add(proportionaMoney).doubleValue();
                // 添加首充历史记录
                this.slfRechargeMapper.insertFirstChargeHistory(userId,rechargeMoney,new BigDecimal(proportionValue.toString()),new BigDecimal(lfb),firstChargeThresholdId);
          }
    	  
      }
      	/**
      	 *活动累计充值返现
      	 */
      	Integer accumulativeNumber=calculationAccumulativeRechargeMoneyProportion(new BigDecimal(recharge));
      	Integer accumulativeNumberAndRecharge=calculationAccumulativeRechargeMoneyProportion(money.add(new BigDecimal(recharge)));
      	// 累计充值有档位
      	if(accumulativeNumberAndRecharge!=null){
      		List<Map<String,Object>> firstChargeProportionValueList= this.slfRechargeMapper.queryAccumulativeRechargeMoneThreshold();
          	BigDecimal totalMoney=new BigDecimal(0);
      		if(accumulativeNumber==null){
      			//之前的充值历史未达到最低档位 
      			  // 遍历获取档位对应反币数据
      			  for (int i = 0; i < accumulativeNumberAndRecharge+1; i++) {
      				 BigDecimal thresholdValue=new BigDecimal(firstChargeProportionValueList.get(i).get(ACCUMULATIVE_RECHARGE_MONEY_KEY).toString());
      				 BigDecimal proportionValue=new BigDecimal(firstChargeProportionValueList.get(i).get(ACCUMULATIVE_RECHARGE_MONEY_VALUE).toString());
      				 BigDecimal multiply= thresholdValue.multiply(proportionValue).setScale(0,BigDecimal.ROUND_DOWN);
      				 totalMoney= totalMoney.add(new BigDecimal(multiply.intValue()));
      				  this.slfRechargeMapper.insertAccumulativeRechargeMoneyHistory(userId,thresholdValue,proportionValue,multiply);
      			  }
      		}else{
      			// 累计返回 5档， 充值+累计返回6档 实际该的为6 档  所以+1 
      			for (int i = accumulativeNumber+1; i <=accumulativeNumberAndRecharge; i++) {
      				 BigDecimal thresholdValue=new BigDecimal(firstChargeProportionValueList.get(i).get(ACCUMULATIVE_RECHARGE_MONEY_KEY).toString());
      				 BigDecimal proportionValue=new BigDecimal(firstChargeProportionValueList.get(i).get(ACCUMULATIVE_RECHARGE_MONEY_VALUE).toString());
      				 BigDecimal multiply= thresholdValue.multiply(proportionValue).setScale(0,BigDecimal.ROUND_DOWN);
      				 totalMoney= totalMoney.add(new BigDecimal(multiply.intValue()));
      				  this.slfRechargeMapper.insertAccumulativeRechargeMoneyHistory(userId,thresholdValue,proportionValue,multiply);
					}
      		}
      		lfb=new BigDecimal(lfb).add(totalMoney).doubleValue();
      	}
      	return lfb;
	
	}
	
    
    
    
    
    

}
